/**
 * Created by 小敏哥 on 2017/7/12.
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Popup, Toast, Modal} from 'antd-mobile'
import FooterAlert from '../../components/remindHome/FooterAlert' //底部弹窗
//actions
import * as carsActions from '../../actions/remindCarAction';

//接口
import CarsServiece from '../../services/CarsServiece';
import YearlyInspectionService from '../../services/YearlyInspectionService';

//常用工具类
import userHelper from '../../utils/userHelper';
import common from '../../utils/common';
import apiHelper from '../../services/apiHelper';
import style from './index.scss';
import urlOperation from '../../utils/urlOperation';
import typeOfBrowser from '../../utils/typeOfBrowser';
import SendCxytjMessage from '../../utils/sendCxytjMessage';
import {getWeixinConfig, getSliderTips} from '../../actions/homeAction';
import ReModal from '../../components/common/reModal';
import NotYetTips from '../../components/calculatorOfYearlyCheck/notYetTips';
import TipsBar from '../../components/Home/tipsBar';
import appVersion from "../../utils/appVersion";
import jsApi from "../../utils/cx580.jsApi";

//资源
let progresBoxBg = './images/progresBoxBg.png'; //圆形进度条背景图
let errorMsg = '系统繁忙，请稍后再试';//错误提示信息

class RemindHome extends Component {
    constructor(props) {
        super(props);
        this.host = apiHelper.production ? 'https://annualcheck.cx580.com' : 'http://192.168.1.165:7083';
        this.state = {
            carId: '', //车辆ID
            carNumber: '', //车牌
            registerDate: '', //车辆注册日期（yyyy-MM-dd）
            checkDate: '', //车辆检验日期（yyyy-MM）
            carCode: '', //车身架号
            engineNumber: '', //发动机号
            state: '-1', //年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废
            agentFlag: true, //年检类型：true为6年新车年检；false为上线年检
            days: 0, //天数
            orderId: '', //订单id，app年检提醒需要（跟据userType区分渠道）
            orderDetailUrl: '', //订单详情URL（跟据userType区分渠道）
            checkDateText: '', //车辆检验日期（YYYY年MM月DD日）
            beginCheckDateText: '', //开始办理年检的日期（YYYY年MM月DD日）
            isRemind: false, //已预约提醒
            validateFlag: 1, //车牌是否支持年检验证 1：支持年检；0：不支持年检
            validateFlagDone: false, //已经请求过数据
            inspectionValidateMsg: '很抱歉，我们尚未开通您车牌所在地的年检业务！', //不支持年检办理的提示语
            bizFlag: 3,//是否支持办理1:免检；2:上线检；3:不可办理
            sliderTipsText: '',//滚动提示文字
        };
        this.goToOrderDetail = this.goToOrderDetail.bind(this);
        if (typeOfBrowser.getChannelOfBrowser() == 'weixin') {
            //尽可能快的屏蔽微信分享
            this.WeXinOperation();
        }
        //标记入口为年检提醒
        sessionStorage.setItem('projectType', 'remind');
    }

    //兼容微信后退，防止后退后报错
    exceptionBack(back, stay, toUrl) {
        history.go(-3);
    }

    WeiXinConfig(config) {
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: config.appId, // 必填，公众号的唯一标识
            timestamp: config.timestamp, // 必填，生成签名的时间戳
            nonceStr: config.nonceStr, // 必填，生成签名的随机串
            signature: config.signature,// 必填，签名，见附录1
            jsApiList: ['hideOptionMenu', 'closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(() => {
            wx.hideOptionMenu();
        });
    }

    //微信屏蔽分享功能
    WeXinOperation() {
        this.props.dispatch(getWeixinConfig({signUrl: location.href}, (result) => {
            this.WeiXinConfig(result);
            //切换页面时再次触发微信配置
            window.addEventListener('hashchange', (e) => {
                this.WeiXinConfig(result);
            }, false);
        }))
    }


    componentWillMount() {
        /*window.cxyPageResume = function () {
         window.location.reload();
         }*/
    }

    //获取用户信息
    getInitData() {
        try {
            let postData = {};
            if (!this.props.params.carId && !this.props.params.carNumber && navigator.userAgent.indexOf("appname_cxycwz") > -1) {
                setTimeout(() => {
                    userHelper.getUserIdAndTokenWithCallBack(data => {
                        //旧版本，可以从getsymbol拿到车辆信息
                        if (data.carId) {
                            let {carId, carNumber} = data;
                            postData = {
                                carId: carId,
                                carNumber: carNumber
                            };
                            common.setViewTitle(decodeURIComponent(postData.carNumber) + '的年检信息');
                            this.getData(postData); //获取数据
                        }
                        else {
                            //新版app，从getcar获取车辆信息
                            userHelper.getCurrentCar(data => {
                                let {carId, carNumber} = data;
                                postData = {
                                    carId: carId,
                                    carNumber: carNumber
                                };
                                common.setViewTitle(decodeURIComponent(postData.carNumber) + '的年检信息');
                                this.getData(postData); //获取数据
                            })
                        }
                    })
                }, 250);//延迟 避免JSDK还未初始化
            }
            else {
                postData = {
                    carId: this.props.params.carId,
                    carNumber: this.props.params.carNumber
                };
                common.setViewTitle(decodeURIComponent(postData.carNumber) + '的年检信息');
                this.getData(postData); //获取数据
            }

            SendCxytjMessage.sendMessage({
                eventId: 'H5_P_Interspection_EnterRemindpage', //事件标记
                productId: 'allInspectionReminder',
                attr1: '进入年检提醒页面' //属性1
            });

        } catch (error) {
            Toast.info('系统繁忙，请稍后再试', 3, () => common.closeAppView())
        }
    }

    componentDidMount() {
        //获取滚动信息条
        this.props.dispatch(getSliderTips({positionCode: 'sy'}, (result) => {
            this.getInitData();
            this.setState({
                sliderTipsText: result.title,
            });
        }));

        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            //隐藏右侧功能按钮
            setTimeout(() => {
                jsApi.call({
                    "commandId": "",
                    "command": "customizeTopRightButton",
                    "data": {
                        "list": []
                    }
                }, function (data) {
                })
            }, 200)
        }
    }

    componentWillUnmount() {

    }

    toUrl(url) {
        //此处app 用内部路由跳转会发生异常
        /*if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
         let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&appType=remind/#${url}`;
         location.href = finalUrl;
         }
         else {*/
        this.context.router.push(url);
        // }
    }

    //打开新view跳转

    toUrlByOpenNewView(url) {
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            let showTitleLayout = appVersion.getMainVersionByCount() >= 6.33 ? 'true' : 'false';
            //此处增加app用于识别年检提醒
            let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&appType=remind#${url}`;
            if (appVersion.getMainVersionByCount() >= 6.33) {
                finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&api_version=3&appType=remind#${url}`;
            }
            //common.openNewBrowserWithURL(finalUrl);


            jsApi.call({
                "commandId": "",
                "command": "openNewBrowserWithURL",
                "data": {
                    "url": finalUrl,
                    "umengId": "cfw_youkachongzhi",
                    "showTitleLayout": showTitleLayout //是否显示到导航栏
                }
            }, function (data) {

            });
        }
        else {
            this.context.router.push(url);
        }
    }


    //构建跳转地址
    getInspectionUrl() {
        let {carId, carNumber, bizFlag} = this.state;
        let url = `/confirmOrder/${carId}/${encodeURIComponent(carNumber)}`;
        /*let detailUserType = '';
         let url = '';
         carNumber = encodeURIComponent(carNumber); //url编码
         let t = new Date().getTime();
         if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
         detailUserType = 'app';
         url = `${this.host}/inspection/index.html?t=${t}&detailUserType=${detailUserType}#/confirmOrder/${carId}/${carNumber}/${bizFlag}`;
         }
         else {
         detailUserType = urlOperation.getParameters().userType;
         let userId = urlOperation.getParameters().userId;
         let userType = urlOperation.getParameters().userType;
         let token = urlOperation.getParameters().token;
         let authType = urlOperation.getParameters().authType;
         url = `${this.host}/inspection/index.html?t=${t}&detailUserType=${detailUserType}&userId=${userId}&userType=${userType}&token=${token}&authType=${authType}#/confirmOrder/${carId}/${carNumber}/${bizFlag}`
         }*/
        return url;
    }

    /**
     * 跳转到办理说明页面
     * @param {*string} url
     */
    toProcessDetail() {
        let {bizFlag} = this.state;
        SendCxytjMessage.sendMessage({
            eventId: 'allInspectionReminder_exit3', //事件标记
            productId: 'allInspectionReminder',
            attr1: '办理流程' //属性1
        });

        //判断车牌是否支持年检办理
        /*if (!validateFlagDone) {*/
        this.inspectionValidate(() => {

            let url = this.getInspectionUrl();
            url = encodeURIComponent(url);//url编码

            if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
                //此处增加app用于识别年检提醒
                let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app#/remindProcessDetail/${url}/${this.state.bizFlag}`;
                if (appVersion.getMainVersionByCount() >= 6.33) {
                    finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&api_version=3#/remindProcessDetail/${url}/${this.state.bizFlag}`;
                }
                common.openNewBrowserWithURL(finalUrl);
            }
            else {
                this.toUrl(`remindProcessDetail/${url}/${this.state.bizFlag}`);
            }
        });
        /*     return;
         } else {
         if (validateFlag != 1) {
         Toast.info(inspectionValidateMsg)
         return;
         }
         }*/


    }

    //获取车辆信息
    getData(postData) {
        Toast.hide();
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        CarsServiece.view(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                data = data.data;
                if (data.checkDate) { //存在注册时间
                    let checkDateArr = data.checkDate.split('-');

                    if (checkDateArr.length > 1) { //格式合法
                        data.checkDateText = new Date(checkDateArr[0], checkDateArr[1]).toJSON().substr(0, 10); //获取yyyy-MM-dd
                        data.checkDateText = this.showDate(data.checkDateText);//转为yyyy年mm月dd日
                        data.beginCheckDateText = new Date(checkDateArr[0], checkDateArr[1] - 2).toJSON().substr(0, 8) + '01'; //获取yyyy-MM-dd
                        data.beginCheckDateText = this.showDate(data.beginCheckDateText, 2); //转为yyyy年mm月
                    }
                }
                data.state += ''; //转为字符串
                data.isRemind = data.appointment; //是否已经预约
                this.setState(Object.assign({}, this.state, postData, data), () => {
                    this.props.dispatch(carsActions.addCarInfo(this.state)); //提交数据到全局state
                    if (['0', '1', '2', '3'].indexOf(this.state.state) !== -1) {
                        this.clearProgres(); //先重置圆环
                        this.showNumber(this.refs.days, 630, this.state.days, 1500); //动态显示数据
                        this.showProgres(100, Math.ceil((this.state.days / 630) * 100), 1500); //动态显示进度条
                    }
                })
            } else {
                Toast.info(data.msg, 2)
            }
        }, (e) => {
            Toast.hide();
            Toast.info(errorMsg)
        })

    }

    /**
     * 判断车牌是否支持年检验证
     */
    inspectionValidate(callBack) {
        let {carId, carNumber} = this.state;
        let postData = {
            carId: carId,
            carNumber: carNumber
        };
        Toast.loading('', 30);
        YearlyInspectionService.inspectionValidate(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                data = data.data;
                if (data.bizFlag == '1' || data.bizFlag == '2') {
                    this.setState({
                        validateFlag: data.bizFlag == '1' || data.bizFlag == '2',//1为免检，2为上线检
                        bizFlag: data.bizFlag,//年检类型
                    });
                    //粤牌车检测到过线检时弹框提示，免检有效日期20天内需要弹出提示框，提示由后端决定
                    if (data.msg) {
                        ReModal.confirm(data.msg, () => {
                            callBack();
                            SendCxytjMessage.sendMessage({
                                eventId: 'H5_E_Interspection_popup_ClickHandle', //事件标记
                                productId: 'allInspectionReminder',
                                attr1: '前往办理' //属性1
                            });
                        }, () => {
                            SendCxytjMessage.sendMessage({
                                eventId: 'H5_E_Interspection_popup_ClickCancer', //事件标记
                                productId: 'allInspectionReminder',
                                attr1: '点击取消' //属性1
                            });
                        }, {okText: '前往办理'});
                    }
                    else {
                        //跳转到办理说明页面
                        setTimeout(callBack, 0);
                    }
                } else {

                    if (data.state == 0) {
                        //未进入年检周期时做特殊弹窗处理
                        if (data.registerDate && data.checkDate) {
                            ReModal.showOnlyComponent(<NotYetTips registerDate={data.registerDate}
                                                                  expiryDate={data.checkDate} close={() => {
                                ReModal.close();
                                SendCxytjMessage.sendMessage({
                                    eventId: 'H5_E_Interspection_popup_ClickCancer', //事件标记
                                    productId: 'allInspectionReminder',
                                    attr1: '点击取消' //属性1
                                });
                            }} updateCallback={() => {
                                this.getCheckDate();
                                ReModal.close();
                            }}/>);
                        }
                        else {
                            ReModal.confirm(data.msg, () => {
                                SendCxytjMessage.sendMessage({
                                    eventId: 'H5_E_Interspection_popup_Recalculate', //事件标记
                                    productId: 'allInspectionReminder',
                                    attr1: '点击重新计算' //属性1
                                });
                                this.toUrl(`/calculatorOfYearlyCheck/${carNumber}/${carId}`);
                            }, () => {
                                callBack();
                                SendCxytjMessage.sendMessage({
                                    eventId: 'H5_E_Interspection_popup_ClickCancer', //事件标记
                                    productId: 'allInspectionReminder',
                                    attr1: '点击取消' //属性1
                                });
                            }, {okText: '重新计算'})
                        }
                    }
                    else {
                        ReModal.alert(data.msg);
                    }
                }
            } else {
                Toast.info(data.msg)
            }
            this.setState({
                validateFlagDone: true
            }, () => {
                this.props.dispatch(carsActions.updateCarInfo(this.state)); //提交数据到全局state
            })
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        })
    }

    /**
     * 获取最新的检验有效期
     */
    getCheckDate() {
        let {carId, carNumber, registerDate, checkDate, carCode, engineNumber} = this.state;

        Toast.loading('', 0);
        let postData = {
            registerDate: registerDate
        };
        YearlyInspectionService.inspectionCheckList(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                data = data.data;
                checkDate = data.dateList[0].checkDate; //获取最后一次的检验有效期
                let postData = {
                    carId: carId, //车辆id
                    carNumber: carNumber, //车牌号码
                    registerDate: registerDate, //车辆注册日期
                    checkDate: checkDate, //车辆检验日期
                    carCode: carCode, //车身架号
                    engineNumber: engineNumber, //发动机号
                    updateMode: 1,//优先从中大获取数据
                };
                this.upCarData(postData); //更新车辆信息
            } else {
                Toast.info(data.msg)
            }
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        });
        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_Interspection_popup_Updatetime', //事件标记
            productId: 'allInspectionReminder',
            attr1: '点击更新年检时间' //属性1
        });

    }

    /**
     * 保存预约记录
     */
    addRecord() {
        let {carId, carNumber, checkDate, beginCheckDateText, isRemind} = this.state;
        let appointment_date = beginCheckDateText.replace(/[年|月]/g, '-').replace(/[日]/g, '');

        Toast.loading('', 0);
        let postData = {
            carId: carId, //车辆id
            carNumber: carNumber, //车牌号
            check_date: checkDate, //检验有效期
            appointment_date: appointment_date //预约日期
        };
        YearlyInspectionService.recordAddRecord(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                //预约成功
                if (!isRemind) {
                    this.setState({
                        isRemind: true
                    })
                }

                this.showFooterAlert('2');//显示预约成功

            } else {
                Toast.info(errorMsg)
            }
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        })
    }

    /**
     * 更新车辆信息
     */
    upCarData(postData) {
        Toast.loading('', 0);
        CarsServiece.update(postData).then(data => {
            if (data.code == '1000') {
                CarsServiece.view(postData).then(data => {
                    Toast.hide();
                    data = data.data;
                    if (data.checkDate) { //存在注册时间
                        console.log("存在注册时间");
                        let checkDateArr = data.checkDate.split('-');

                        if (checkDateArr.length > 1) { //格式合法
                            console.log("格式合法");
                            data.checkDateText = new Date(checkDateArr[0], checkDateArr[1]).toJSON().substr(0, 10);//获取yyyy-MM-dd
                            data.checkDateText = this.showDate(data.checkDateText); //转为yyyy年mm月dd日
                            data.beginCheckDateText = new Date(checkDateArr[0], checkDateArr[1] - 2).toJSON().substr(0, 8) + '01' //获取yyyy-MM-dd
                            data.beginCheckDateText = this.showDate(data.beginCheckDateText, 2);//转为yyyy年mm月
                        }
                    }
                    data.state += ''; //转为字符串
                    data.isRemind = data.appointment; //是否已经预约
                    this.setState(Object.assign({}, this.state, postData, data), () => {
                        this.props.dispatch(carsActions.updateCarInfo(this.state)); //提交数据到全局state

                        this.clearProgres(); //先重置圆环
                        this.showNumber(this.refs.days, 630, this.state.days, 1500);//动态显示数据
                        this.showProgres(100, Math.ceil((this.state.days / 630) * 100), 1500); //动态显示进度条
                    })
                });
            } else {
                Toast.info(data.msg)
            }
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        })
    }

    getOrderDetailUrl(data, callBack) {
        Toast.loading('', 0);
        CarsServiece.getOrderDetail(data).then((result) => {
            Toast.hide();
            if (result.code == '1000') {
                callBack(result.data.uri);
            }
            else {
                Toast.info(result.msg)
            }
        })
    }

    /**
     * 动态显示数字
     * @param {*object} e dom对象
     * @param {*number} start 开始时数字
     * @param {*number} end 结束时数字
     * @param {*number} 速度 多少毫秒完成 默认1000毫秒
     */
    showNumber(e, start, end, ms = 1000) {
        let end_ms = ms - 200; //结束的时间提前200毫秒
        ms = Math.floor(ms / Math.abs(end - start))
        let delNum = 1 //每次应该减的数字
        if (ms < 4) {
            delNum = Math.floor(4 / ms)
        }
        console.log("最终的数字：", end);
        let timeId = setInterval(() => {
            try {
                if (start < end) {
                    start += delNum; //由小变大
                    if (start >= end) {
                        clearInterval(timeId)
                    }
                } else {
                    start -= delNum; //由大变小
                    if (start <= end) {
                        clearInterval(timeId)
                    }
                }

                e.innerHTML = parseInt(start)
            } catch (error) {
                clearInterval(timeId)
            }

        }, ms);

        setTimeout(function () {
            clearInterval(timeId);
            e.innerHTML = parseInt(end)
        }, end_ms)
    }

    /**
     * 动态显示进度条
     * @param {*number} start 开始时进度 0-100
     * @param {*number} end 结束时进度 0-100
     * @param {*number} 速度 多少毫秒完成 默认1000毫秒
     */
    showProgres(start, end, ms = 1000) {
        ms = Math.floor(ms / Math.abs(end - start));
        let clientWidth = document.documentElement.clientWidth;
        clientWidth = clientWidth > 540 ? 540 : clientWidth;
        let bl = clientWidth / 375;

        if (start < end) {
            //从小到大
        } else {
            //从大到小
            let iLeft = 0; //控制左边 占比35%
            let iTop = 0; //控制上边 占比30%
            let iRight = 0; //控制右边 占比35%

            let leftBottom = 0; //左边的bottom

            let timeId = setInterval(() => {
                try {
                    --start;
                    if (start >= 64) {
                        //大于60%
                        ++iRight;
                        this.refs.grayCircularBoxRight.style.top = (172 - iRight * Math.floor(143 / 35)) + 'px'
                        if (start === 64) {
                            this.refs.grayCircularBoxRight.style.top = '0px'; //避免还存在多余的进度
                        }
                    } else if (start >= 34) {
                        //大于60%
                        ++iTop;
                        this.refs.grayCircularBoxTop.style.width = (iTop * Math.ceil(112 / 30)) + 'px'
                    } else {
                        ++iLeft;
                        leftBottom = (143 - (iLeft * Math.ceil(143 / 35)));
                        leftBottom = leftBottom < 6 ? 6 : leftBottom;//
                        this.refs.grayCircularBoxLeft.style.bottom = leftBottom + 'px'
                    }
                    if (start <= end) {
                        clearInterval(timeId)
                    }
                } catch (error) {
                    clearInterval(timeId)
                }
            }, ms)
        }
    }

    /**
     * 还原进度条
     */
    clearProgres() {
        this.refs.grayCircularBoxRight.style.top = '';
        this.refs.grayCircularBoxTop.style.width = '';
        this.refs.grayCircularBoxLeft.style.bottom = '';
    }

    /**
     * 显示日期 年月||年月日
     * @param {*date} date 日期 格式：YYYY-MM-DD
     * @param {*string} type 日期类型 1、年月入；2、年月；    默认等于年月日
     */
    showDate(date, type = '1') {
        let arr = date.split('-');
        if (arr.constructor !== Array || arr.length < 3) {
            return date; //格式不合法 返回原数据
        }
        switch (type) {
            case '1':
                date = arr[0] + '年' + arr[1] + '月' + arr[2] + '日';
                break;
            case '2':
                date = arr[0] + '年' + arr[1] + '月';
                break;
            default:
                date = arr[0] + '年' + arr[1] + '月' + arr[2] + '日';
        }
        return date
    }

    /**
     * 显示底部弹窗
     */
    showFooterAlert(type = '1') {
        let {days, isRemind} = this.state;

        let props = {
            days: days, //天数
            type: type,//底部弹窗类型：1、未到年检周期。2、预约成功
            isRemind: isRemind, //已预约提醒
            close: () => Popup.hide(),
            clickBtn: btn => {
                Popup.hide(); //隐藏

                if (type == '1') {
                    if (btn == 'leftBtn') {
                        SendCxytjMessage.sendMessage({
                            eventId: 'allInspectionReminder_exit8', //事件标记
                            productId: 'allInspectionReminder',
                            attr1: '底部弹窗—继续办理' //属性1
                        });
                        this.toProcessDetail(); //跳转到办理说明页
                    } else if (btn == 'rightBtn') {
                        if (!isRemind) {
                            //未预约过短信提醒
                            this.addRecord(); //预约提醒
                        }
                        SendCxytjMessage.sendMessage({
                            eventId: 'allInspectionReminder_event5', //事件标记
                            productId: 'allInspectionReminder',
                            attr1: isRemind ? '底部弹窗—暂不办理' : '底部弹窗—短信通知' //属性1
                        });
                    }

                } else {
                    // console.log("预约成功: 点击了：", btn)
                }
            }
        };
        Popup.show(<FooterAlert {...props} />, {animationType: 'slide-up'}
        );
    }

    /**
     * 判断是否已经登录
     */
    checkLogin(state) {
        //carNumber无值，初始化尚未完成，按按钮不执行操作
        /* if(!this.state.carNumber){
             return;
         }*/
        userHelper.getUserIdAndTokenWithCallBack(data => {
            let {userId, token,} = data;

            if (state == '-1') { //补充年检资料
                let {carId, carNumber} = this.state;
                this.toUrl(`/calculatorOfYearlyCheck/${carNumber}/${carId}`);
                SendCxytjMessage.sendMessage({
                    eventId: 'H5_E_Interspection_ClickAddMeterials', //事件标记
                    productId: 'allInspectionReminder',
                    attr1: '补充年检资料' //属性1
                });
            } else if (state == '0') {
                this.showFooterAlert(); //未进入预约期
            } else {
                SendCxytjMessage.sendMessage({
                    eventId: 'H5_E_Interspection_ClickHandle', //事件标记
                    productId: 'allInspectionReminder',
                    attr1: '立即办理—现有流程' //属性1
                });
                this.toProcessDetail(); //跳转到办理说明页
            }

        })
    }

    /**
     * 计算有误
     */
    calculation() {
        let {carId, carNumber} = this.state;
        this.toUrl(`/calculatorOfYearlyCheck/${carNumber}/${carId}`);
        SendCxytjMessage.sendMessage({
            eventId: 'allInspectionReminder_exit2', //事件标记
            productId: 'allInspectionReminder',
            attr1: '计算有误' //属性1
        });
    }

    /**
     * 获取页面色系
     * @param {*number} state 状态
     */
    getColor(state) {
        let color = style.homeRed;

        if (state == '-1') {
            color = style.homeGray
        } else if (state == '0') {
            color = ''; //默认颜色 所以不需要修改
        } else if (state == '1') {
            color = style.homeBlue
        } else if (state == '6') {
            color = style.homeBlue
        }

        return color
    }

    /**
     * 渲染文字提醒
     */
    getHomeMsgBox(state) {
        let {beginCheckDateText, bizFlag} = this.state;

        let jsxArr = { //年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废
            '-1': <div className={style.homeMsgBox}>
                <div>请补充车辆信息后查看年检状态</div>
                <p>逾期状态下，被查将扣车扣分并在事故中<br/>不能出险</p>
            </div>,
            '0': <div className={style.homeMsgBox}>
                <div>目前尚无需进行年检，可放心驾驶</div>
                <p>您可于 {beginCheckDateText} 预约年检办理</p>
            </div>,
            '1': <div className={style.homeMsgBox}>
                <div>车辆已进入年检周期，请尽快办理</div>
                <p>逾期后车辆出事故不能报保险，<br/>车上路被查将扣车扣分</p>
            </div>,
            '2': <div className={style.homeMsgBox}>
                <div>车辆已逾期，请尽快办理</div>
                <p>逾期后车辆出事故不能报保险，<br/>车上路被查将扣车扣分</p>
            </div>,
            '3': <div className={style.homeMsgBox}>
                <div>车辆已逾期，请尽快办理</div>
                <p>逾期后车辆出事故不能报保险，<br/>车上路被查将扣车扣分</p>
            </div>,
            '4': <div className={style.homeMsgBox}>
                <div>年检已连续逾期两次，请尽快办理</div>
                <p>请您在“下一个年检有效期内”完成年检办理，<br/>不然车辆会直接报废处理哦</p>
            </div>,
            '5': <div className={style.homeMsgBox}>
                <div>年检已连续逾期三次，需强制报废</div>
                <p>请勿驾驶该车辆上路，被查时将收缴车辆，<br/>并面临罚款和吊销驾驶证的处罚</p>
            </div>,
            '6': <div className={style.homeMsgBox}>
                <div>我们正在办理您的年检订单</div>
                <p>详细信息可在订单详情中查看</p>
            </div>
        };
        /*  if ((state == 2 || state == 3) && bizFlag == 2) {
         //过线检需要有特殊的提示显示
         return <div className={style.homeMsgBox}>
         <div>该车辆已逾期{this.state.days}天，需上线检测</div>
         <p>逾期超过一年时必须办理上线检，<br />逾期车辆驾驶被查将扣车扣分并在事故中不能出险</p>
         </div>
         }
         else {
         return jsxArr[state] || jsxArr['-1']
         }
         */
        return jsxArr[state] || jsxArr['-1']
    }

    //根据获取的detail地址跳转到相应的目录
    goToOrderDetail() {
        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_Interspection_ClickContinue', //事件标记
            productId: 'allInspectionReminder',
            attr1: '继续办理年检' //属性1
        });
        this.getOrderDetailUrl({orderId: this.state.orderId}, (uri) => {
            /*let detailUserType = urlOperation.getParameters().userType;
             let userId = urlOperation.getParameters().userId;
             let userType = urlOperation.getParameters().userType;
             let token = urlOperation.getParameters().token;
             let authType = urlOperation.getParameters().authType;
             let url=`${this.host}/inspection/index.html?detailUserType=${detailUserType}&userId=${userId}&userType=${userType}&token=${token}&authType=${authType}#/${uri}`;
             common.openNewBrowserWithURL(url)*/
            this.toUrlByOpenNewView('/' + uri);
        })
    }

    /**
     * 渲染底部按钮
     */
    showFooterBtn(state) {
        let {isRemind, bizFlag} = this.state;
        let btn = '';
        if (state == '6') {
            btn = <div className={style.btnWhite} onClick={this.goToOrderDetail}>{this.state.msg}</div>
        } else if (state == '-1') {
            btn = <div className={style.btn} onClick={() => this.checkLogin(state)}>补充年检资料</div>
        } else if (bizFlag != 3) {
            btn =
                <div className={style.btn} onClick={() => this.checkLogin(state)}>立即办理{isRemind ? ' (已预约提醒)' : ''}</div>
        } else {
            btn = <div className={style.btn + ' ' + style.notClickBtn}>立即办理</div>
        }
        return btn
    }


    /*    goToSingleProcessDetail(bizFlag) {
            let url = `/processDetailsView/${bizFlag}`;
            if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
                //此处增加app用于识别年检提醒
                let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app/#${url}`;
                common.openNewBrowserWithURL(finalUrl);
            }
            else {
                this.toUrl(url);
            }
            SendCxytjMessage.sendMessage({
                eventId: 'H5_E_Interspection_ClickInterspectiontype', //事件标记
                productId: 'allInspectionReminder',
            });
        }*/

    /**
     * 点击常见问题
     */
    clickProgresIssue() {
        /*let detailUserType='';
         let url='';
         if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
         detailUserType = 'app';
         url = `${this.host}/inspection/index.html?detailUserType=${detailUserType}/#/questions`;
         }
         else {
         detailUserType = urlOperation.getParameters().userType;
         let userId = urlOperation.getParameters().userId;
         let userType = urlOperation.getParameters().userType;
         let token = urlOperation.getParameters().token;
         let authType = urlOperation.getParameters().authType;
         url = `${this.host}/inspection/index.html?detailUserType=${detailUserType}&userId=${userId}&userType=${userType}&token=${token}&authType=${authType}/#/questions`
         }*/
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            //此处增加app用于识别年检提醒
            let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app#/questions`;
            if (appVersion.getMainVersionByCount() >= 6.33) {
                finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&api_version=3#/questions`;
            }
            common.openNewBrowserWithURL(finalUrl);
        }
        else {
            this.toUrl('/questions');
        }

        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_Interspection_ClickQA', //事件标记
            productId: 'allInspectionReminder',
            attr1: '常见问题' //属性1
        });
        //  common.openNewBrowserWithURL(url)
    }

    /**
     * 点击更新信息
     */

    /*    clickDateMsg() {
            SendCxytjMessage.sendMessage({
                eventId: 'allInspectionReminder_event2', //事件标记
                productId: 'allInspectionReminder',
                attr1: '点击更新年检信息' //属性1
            });

            ReModal.confirm(<div className={style.confirmMessage}>
                <div className={style.main}>确认已办理过本次年检?</div>
                <div className={style.tips}>确认后将为您重新计算</div>
            </div>, () => {
                SendCxytjMessage.sendMessage({
                    eventId: 'allInspectionReminder_event3', //事件标记
                    productId: 'allInspectionReminder',
                    attr1: '确认更新年检信息' //属性1
                });
                this.getCheckDate()
            });

        }*/

    showIconPromptToast(state) {
        SendCxytjMessage.sendMessage({
            eventId: 'allInspectionReminder_event1', //事件标记
            productId: 'allInspectionReminder',
            attr1: '查看逾期详细说明' //属性1
        });
        let {days} = this.state;
        let toasts = {
            '2': `车辆未按规定在检验有效期内完成年检，目前已逾期${days}天。请您尽快处理，否则逾期超过一年，将需要车主本人开车去车管所亲自办理。`,
            '3': `车辆未按规定在检验有效期内完成年检，目前已逾期${days}天。按相关法律规定，需要车主本人开车去车管所亲自办理年检。`,
            '4': `车辆已连续两次年检逾期，请您在“下一次理论上的年检有效期”之内完成车辆上线检测，否则车辆将直接报废。`,
            '5': `车辆未按规定在检验有效期内完成年检，并且逾期次数已连续超过3次。按我国机动车相关法规《机动车强制报废标准》的规定，车辆已达强制报废条件。请勿再驾驶此车上路，否则将被收缴，并面临罚款和吊销驾驶证的处罚`
        };
        if (toasts[state]) {
            Toast.info(toasts[state])
        }
    }

    //构建当前年检类型提示
    structInspectionItem(state, bizFlag, nextState) {
        if (state == '0') {
            return <span className={style.inspectionTypeItem}>暂无需年检</span>
        }
        else if (bizFlag != '3') {
            return <span className={style.inspectionTypeItem}>{bizFlag == '1' ? '6年免检' : '上线检'}</span>
        }
        else if (state == '5') {
            return <span className={style.inspectionTypeItem + ' ' + style.disableInspectionType}>报废</span>
        }
        else if (state == '-1') {
            return <span className={style.inspectionTypeItem + ' ' + style.disableInspectionType}>未知</span>
        }
    }

    gotoYearlyCheckDetail() {
        if (this.state.state != '6' && this.state.state != '-1') {
            SendCxytjMessage.sendMessage({
                eventId: 'H5_E_Interspection_ClickCircle', //事件标记
                productId: 'allInspectionReminder',
                attr1: '点击圆圈' //属性1
            });

            this.toUrl(`/yearlyCheckDetail/${encodeURIComponent(this.state.carNumber)}/${ this.state.carId}/check`);
        }
    }

    render() {
        console.log("this.state", this.state);
        let {state, checkDateText, beginCheckDateText, bizFlag} = this.state;

        let color = this.getColor(state);//获取颜色
        let texts = { //年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废；6年审订单办理中
            '-1': <i>小心年检逾期</i>,
            '0': <i>距年检可预约天数</i>,
            '1': <i>距年检到期天数</i>,
            '2': <i onClick={() => this.showIconPromptToast(state)}>该车辆已逾期天数</i>,
            '3': <i onClick={() => this.showIconPromptToast(state)}>该车辆已逾期天数</i>,
            '4': <i onClick={() => this.showIconPromptToast(state)}>该车辆存在报废风险</i>,
            '5': <i onClick={() => this.showIconPromptToast(state)}>请勿上路驾驶</i>,
            '6': <i><span style={{fontWeight: 'normal'}}>请您耐心等待</span></i>
        };
        let daysTexts = {
            '-1': '状态未知',
            '0': '',
            '1': '',
            '2': '',
            '3': '',
            '4': '严重逾期',
            '5': '车辆已报废',
            '6': '年检办理中'
        };

        let daysClassName = ['0', '1', '2', '3'].indexOf(state) !== -1 ? '' : style.font60;

        return (
            <div className={style.box}>
                <div className={style.homeBox + " " + color}>
                    <TipsBar text={this.state.sliderTipsText}/>
                    {/* <div className={style.homeTop}>
                        {state == '-1' ? <p style={{height: '.36rem'}}></p> :
                            <p>检验有效期截止至 — {checkDateText}
                                {state == '6' ? '' :
                                    <span onClick={() => this.calculation()}><span className={style.borderB}>计算有误</span>?</span>
                                }
                            </p>
                        }
                    </div>*/}
                    <div className={style.progresBox}>

                        {/*显示天数或对应的年检状态icon start*/}
                        <div className={style.progres} style={{backgroundImage: `url(${progresBoxBg})`}}
                             onClick={() => {
                                 this.gotoYearlyCheckDetail()
                             }}>
                            <div className={style.progresDaysBox}>
                                <span ref='days' className={daysClassName}>{daysTexts[state]}</span>{texts[state]}
                            </div>
                            {this.structInspectionItem(state, bizFlag)}
                        </div>
                        {/*显示天数或对应的年检状态icon end*/}

                        {/*渐变圆环 start*/}
                        <div className={style.circularBox}>
                            <div className={style.circular1Box}>
                                <div className={style.circular + ' ' + style.circular1}>
                                    <div className={style.hideCircular}></div>
                                </div>
                            </div>
                            <div className={style.circular + ' ' + style.circular2}>
                                <div className={style.hideCircular}></div>
                            </div>
                            <div className={style.whiteCircular}></div>
                            <div className={style.grayCircularBox}>
                                <div ref='grayCircularBoxLeft' className={style.grayCircularBoxLeft}></div>
                                <div ref='grayCircularBoxTop' className={style.grayCircularBoxTop}></div>
                                <div ref='grayCircularBoxRight' className={style.grayCircularBoxRight}></div>
                            </div>
                        </div>
                        {/*渐变圆环 start*/}

                    </div>

                    {/*文字提醒 start*/}
                    {this.getHomeMsgBox(state)}
                    {/*文字提醒 end*/}

                    {/*立即办理按钮 || 查看订单详情按钮 start*/}
                    <div className={style.buttonContainer}>
                        {this.showFooterBtn(state)}
                    </div>
                    {/*立即办理按钮 || 查看订单详情按钮 end*/}

                    {/*已办理过年检 更新按钮 start*/}
                    {/*{
                        ['1', '2', '3', '4', '5'].indexOf(state) != -1 ?
                            <div className={style.homeBtnBottom}>已办理过本次年检？ <span
                                onClick={() => this.clickDateMsg()}>点击更新信息</span></div>
                            :
                            ''
                    }*/}
                    {/*已办理过年检 更新按钮 end*/}
                </div>
                <div className={style.homeFooter} onClick={() => this.clickProgresIssue()}>
                    <img src="./images/remindQuestions.png"/>
                    <span>常见问题</span>
                </div>

            </div>
        )
    }
}

//使用context
RemindHome.contextTypes = {
    router: React.PropTypes.object.isRequired
};

export default connect()(RemindHome);